#include <bits/stdc++.h>
#include <utility>
using namespace std;
struct node {
    long long x,y,step;
    node (int x,int y,int step){
        this->x = x;
        this->y = y;
        this->step = step;
    }
};
long long ans=1000001;
queue<node> Q;
pair<int,int> now;
int n,m;
char corn[301][301];
bool vis[301][301];
map<char,pair<pair<int,int>,pair<int,int>>> tp;
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
void bfs(){
    auto loc = Q.front();
    vis[loc.x][loc.y] = 1;
    Q.pop();
    if (corn[loc.x][loc.y] == '='){
        ans = min(ans,loc.step);
        return;
    }
    for (int i=0;i<4;i++){
        int bx = loc.x+dir[i][0],by = loc.y+dir[i][1];
        if (bx<0 || bx >= n|| by<0 || by >= m) continue;
        if (corn[bx][by] == '#') continue;
        if (vis[bx][by]) continue;
        if (tp.count(corn[bx][by])){
            if (make_pair(bx, by) == tp[corn[bx][by]].first){
                Q.push(node(tp[corn[bx][by]].second.first,tp[corn[bx][by]].second.second,loc.step+1));
            }
            else {
                Q.push(node(tp[corn[bx][by]].second.first,tp[corn[bx][by]].second.second,loc.step+1));
            }
        }
        else {
            Q.push(node(tp[corn[bx][by]].second.first,tp[corn[bx][by]].second.second,loc.step+1));
        }
    }
}
int main(){
    cin>>n>>m;
    for (int i=0;i<n;i++){
        for (int j=0;j<m;j++){
            cin>>corn[i][j];
            if (corn[i][j] == '@') now = make_pair(i, j);
            if (corn[i][j] >= 'A' && corn[i][j] <= 'Z') {
                if (!tp.count(corn[i][j]))  tp[corn[i][j]].first = make_pair(i,j);
                else tp[corn[i][j]].second = make_pair(i,j);
            }
        }
    }
    Q.push(node(now.first,now.second,0));
    vis[now.first][now.second]=1;
    while (!Q.empty()) bfs();
    cout<<ans;
    return 0;
}
